<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CZLJChat v2.0</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 5px;
            padding-left: 20px;
            padding-right: 20px;
            background: linear-gradient(to bottom right, #f8f9f8, #e0e0f0);
            min-height: 98vh;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: background 0.3s ease;
        }
        #chat-container {
            background-color: #ffffff;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            width: calc(100% - 40px);
            max-width: 1000px;
            transition: background-color 0.3s ease, box-shadow 0.3s ease;
        }
        #chat-messages {
            position: relative;
            min-height: 340px;
            max-height: 340px;
            overflow-y: auto;
            margin-bottom: 20px;
            padding: 20px;
            transition: background-color 0.3s ease;
        }
        #chat-messages::before {
            content: "我是CZLJChat，很高兴见到你！";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 24px;
            color: #000;
            opacity: 0.4;
            font-weight: bold;
            z-index: 1;
            white-space: nowrap;
            transition: color 0.3s ease;
        }
        #chat-messages:has(.message)::before {
            display: none;
        }
        .message {
            margin-bottom: 8px;
            padding: 5px 10px;
            border-radius: 10px;
            display: flex;
            align-items: flex-start;
            line-height: 1.5;
            position: relative;
            transition: background-color 0.3s ease;
        }
        .user-message {
            background-color: #e3f2fd;
            margin-left: auto;
            margin-right: 0;
            max-width: 80%;
            width: fit-content;
            padding-top: 0px;
            padding-bottom: 0px;
            transition: background-color 0.3s ease;
        }
        .bot-message {
            background-color: #ffffff;
            margin-right: auto;
            margin-left: 0;
            max-width: 80%;
            width: fit-content;
            transition: background-color 0.3s ease;
        }
        .code-block {
            background-color: #f0f0f0;
            color: #333;
            padding: 10px;
            border-radius: 5px;
            font-family: Consolas, monospace;
            overflow-x: auto;
            white-space: pre-wrap;
            margin: 10px 0;
            position: relative;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        .code-block .code-language {
            position: absolute;
            top: 5px;
            left: 5px;
            padding: 2px 5px;
            font-size: 12px;
            background-color: #444;
            color: #fff;
            border-radius: 3px;
            font-family: Consolas, monospace;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        .code-block .copy-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            padding: 2px 5px;
            font-size: 12px;
            background-color: #444;
            color: #fff;
            border-radius: 3px;
            cursor: pointer;
            font-family: Arial, sans-serif;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        .code-block .copy-btn:hover {
            background-color: #666;
        }
        .code-block .line-numbers {
            float: left;
            width: 40px;
            user-select: none;
            color: #999;
            transition: color 0.3s ease;
        }
        .code-block .line-contents {
            margin-left: 40px;
            transition: color 0.3s ease;
        }
        #input-container {
            position: relative;
        }
        #user-input {
            width: calc(100% - 20px);
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            resize: vertical;
            min-height: 70px;
            max-height: 150px;
            overflow-y: auto;
            background-color: #fafafa;
            transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
        }
        .button-container {
            position: absolute;
            right: 10px;
            bottom: 10px;
            display: flex;
            gap: 8px;
        }
        .left-button-container {
            position: absolute;
            left: 10px;
            bottom: 10px;
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .model-select {
            padding: 4px 8px;
            border: 1px solid #cccccc;
            border-radius: 15px;
            background-color: #ffffff;
            font-size: 12px;
            transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
        }
        .reason-button {
            padding: 4px 8px;
            border: 1px solid #cccccc;
            border-radius: 15px;
            background-color: #ffffff;
            color: #000;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .reason-button.active {
            border-color: #007bff;
            color: #007bff;
            box-shadow: 0 0 3px rgba(0, 123, 255, 0.3);
        }
        #reason-toggle {
            display: none;
            margin-left: 8px;
        }
        .send-button {
            width: 32px;
            height: 32px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.3s ease;
        }
        .send-button:hover {
            background-color: #0056b3;
        }
        .send-button::after {
            content: "➜";
            font-size: 16px;
        }
        .file-upload-label {
            width: 32px;
            height: 32px;
            background-color: #fefefe;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.3s ease;
        }
        .file-upload-label:hover {
            background-color: #eeeeee;
        }
        .file-upload-label::after {
            content: "✚";
            font-size: 16px;
            color: #666666;
            transition: color 0.3s ease;
        }
        #file-input {
            display: none;
        }
        .delete-button {
            width: 32px;
            height: 32px;
            background-color: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.3s ease;
        }
        .delete-button:hover {
            background-color: #bb2d3b;
        }
        .delete-button::after {
            content: "🗑";
            font-size: 16px;
        }
        .send-button.loading::after {
            content: "";
            width: 16px;
            height: 16px;
            border: 2px solid #fff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 0.8s linear infinite;
        }
        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
        @media (max-width: 768px) {
            body {
                padding: 10px;
                background-color: #fff;
            }
            #chat-container {
                padding: 12px;
                border-radius: 8px;
                box-shadow: none;
            }
            #chat-messages {
                min-height: 60vh;
                max-height: 60vh;
                margin-bottom: 15px;
                padding: 8px;
            }
            #chat-messages::before {
                font-size: 18px;
            }
            .message {
                font-size: 14px;
                max-width: 85%;
                margin-bottom: 10px;
                padding: 8px;
            }
            #user-input {
                min-height: 70px;
                max-height: 150px;
                font-size: 14px;
                padding: 8px;
            }
            .send-button,
            .file-upload-label {
                width: 28px;
                height: 28px;
            }
            .send-button::after,
            .file-upload-label::after {
                font-size: 14px;
            }
        }
        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
            background-color: #f0f0f0;
            transition: background-color 0.3s ease;
        }
        .kimi-avatar {
            background-image: url("https://chat.czlj.net/icon/k.png");
            background-size: cover;
        }
        .chatgpt-avatar {
            background-image: url("https://chat.czlj.net/icon/c.png");
            background-size: cover;
        }
        .claude-avatar {
            background-image: url("https://chat.czlj.net/icon/cl.png");
            background-size: cover;
        }
        .deepseek-avatar {
            background-image: url("https://chat.czlj.net/icon/d.png");
            background-size: cover;
        }
        .message-actions {
            position: absolute;
            bottom: 5px;
            display: flex;
            gap: 5px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .user-message .message-actions {
            left: 10px;
        }
        .bot-message .message-actions {
            right: 10px;
        }
        .message:hover .message-actions {
            opacity: 1;
        }
        .copy-message, .delete-message {
            width: 24px;
            height: 24px;
            background-color: #f0f0f0;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 14px;
            color: #333;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        .copy-message:hover, .delete-message:hover {
            background-color: #e0e0e0;
        }
        .copy-message::after {
            content: "📋";
        }
        .delete-message::after {
            content: "🗑";
        }
        body.dark-theme {
            background: linear-gradient(to bottom right, #2c2c2c, #3a3a3a);
            color: #ffffff;
        }
        body.dark-theme #chat-container {
            background-color: #333333;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
        }
        body.dark-theme #chat-messages {
            background-color: #333333;
            color: #ffffff;
        }
        body.dark-theme #chat-messages::before {
            color: #ffffff;
        }
        body.dark-theme .message {
            background-color: #444444;
            color: #ffffff;
        }
        body.dark-theme .user-message {
            background-color: #3a506b;
            color: #ffffff;
        }
        body.dark-theme .bot-message {
            background-color: #444444;
            color: #ffffff;
        }
        body.dark-theme .code-block {
            background-color: #333333;
            color: #e0e0e0;
        }
        body.dark-theme .code-block .code-language {
            background-color: #222222;
            color: #e0e0e0;
        }
        body.dark-theme .code-block .copy-btn {
            background-color: #222222;
            color: #e0e0e0;
        }
        body.dark-theme .code-block .line-numbers {
            color: #999999;
        }
        body.dark-theme #user-input {
            background-color: #2f2f2f;
            border-color: #444444;
            color: #e0e0e0;
        }
        body.dark-theme .model-select {
            background-color: #333333;
            border-color: #444444;
            color: #e0e0e0;
        }
        body.dark-theme .reason-button {
            background-color: #333333;
            border-color: #444444;
            color: #e0e0e0;
        }
        body.dark-theme .reason-button.active {
            border-color: #007bff;
            color: #007bff;
        }
        body.dark-theme .send-button {
            background-color: #0056b3;
        }
        body.dark-theme .send-button:hover {
            background-color: #003d7a;
        }
        body.dark-theme .file-upload-label {
            background-color: #333333;
        }
        body.dark-theme .file-upload-label:hover {
            background-color: #444444;
        }
        body.dark-theme .file-upload-label::after {
            color: #e0e0e0;
        }
        body.dark-theme .delete-button {
            background-color: #a83232;
        }
        body.dark-theme .delete-button:hover {
            background-color: #8c2828;
        }
        body.dark-theme .avatar {
            background-color: #444444;
        }
        body.dark-theme .copy-message, body.dark-theme .delete-message {
            background-color: #444444;
            color: #e0e0e0;
        }
        body.dark-theme .copy-message:hover, body.dark-theme .delete-message:hover {
            background-color: #555555;
        }
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
        body.dark-theme ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        body.dark-theme ::-webkit-scrollbar-track {
            background: #2a2a2a;
        }
        body.dark-theme ::-webkit-scrollbar-thumb {
            background: #555;
            border-radius: 4px;
        }
        body.dark-theme ::-webkit-scrollbar-thumb:hover {
            background: #777;
        }
        .theme-toggle {
            position: absolute;
            top: 20px;
            right: 20px;
            width: 40px;
            height: 40px;
            background-color: #ffffff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            z-index: 100;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        .theme-toggle:hover {
            background-color: #f0f0f0;
        }
        body.dark-theme .theme-toggle {
            background-color: #333333;
        }
        body.dark-theme .theme-toggle:hover {
            background-color: #444444;
        }
        .theme-toggle::after {
            content: "🌙";
            font-size: 20px;
        }
        body.dark-theme .theme-toggle::after {
            content: "☀️";
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/crypto-js.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-light.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.0.0/marked.min.js"></script>
</head>
<body>
    <div class="theme-toggle" id="theme-toggle"></div>
    <div id="chat-container">
        <div id="chat-messages"></div>
        <div id="input-container">
            <div class="left-button-container">
                <select id="model-select" class="model-select">
                    <option value="kimi">Kimi</option>
                    <option value="chatgpt">ChatGPT</option>
                    <option value="claude">Claude</option>
                    <option value="deepseek">DeepSeek</option>
                </select>
                <button id="reason-toggle" class="reason-button">深度思考(R1)</button>
            </div>
            <textarea id="user-input" placeholder="给CZLJChat发送消息"></textarea>
            <div class="button-container">
                <button class="delete-button" onclick="clearChatHistory()"></button>
                <label for="file-input" class="file-upload-label"></label>
                <button class="send-button" onclick="sendMessage()"></button>
            </div>
            <input type="file" id="file-input" accept=".txt,.pdf,.docx,.xls,.xlsx,.json">
        </div>
    </div>

    <script>
        const CONFIG = {
            kimi: {
                API_KEY: "",
                API_URL: "",
                MODEL: "",
                TOKEN_LIMIT: 2048
            },
            chatgpt: {
                API_KEY: "",
                API_URL: "",
                MODEL: "",
                TOKEN_LIMIT: 2048
            },
            claude: {
                API_KEY: "",
                API_URL: "",
                MODEL: "",
                TOKEN_LIMIT: 2048
            },
            deepseek: {
                API_KEY: "",
                API_URL: "",
                MODEL: "",
                REASON_MODEL: "",
                TOKEN_LIMIT: 2048
            }
        };

        let currentModel = 'kimi';
        let isReasonMode = false;
        let fileContent = '';
        let contextMessages = [];
        let isDarkTheme = false;

        document.getElementById('model-select').addEventListener('change', (e) => {
            currentModel = e.target.value;
            document.getElementById('reason-toggle').style.display =
                currentModel === 'deepseek' ? 'block' : 'none';
            localStorage.setItem('currentModel', currentModel);
        });

        document.getElementById('reason-toggle').addEventListener('click', function () {
            isReasonMode = !isReasonMode;
            this.classList.toggle('active');
        });

        document.getElementById('theme-toggle').addEventListener('click', function () {
            isDarkTheme = !isDarkTheme;
            document.body.classList.toggle('dark-theme', isDarkTheme);
            localStorage.setItem('darkTheme', isDarkTheme);
        });

        function addMessage(content, role, model = currentModel) {
            const messagesDiv = document.getElementById('chat-messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}-message`;

            if (role === 'bot') {
                const avatar = document.createElement('div');
                avatar.className = `avatar ${model}-avatar`;
                messageDiv.appendChild(avatar);
            }

            const textDiv = document.createElement('div');
            textDiv.style.flex = '1';

            if (content.includes("```")) {
                const parts = content.split("```");
                parts.forEach((part, index) => {
                    if (index % 2 === 1) {
                        const codeBlock = document.createElement('pre');
                        codeBlock.className = 'code-block';
                        const languageMatch = part.match(/^(\w+)/);
                        const codeLanguage = languageMatch ? languageMatch[1] : 'plaintext';
                        const codeContent = languageMatch ? part.slice(languageMatch[0].length) : part;
                        const trimmedCodeContent = codeContent.trim();
                        codeBlock.innerHTML = `<span class="code-language">${codeLanguage}</span><button class="copy-btn">复制</button><div class="line-numbers"></div><div class="line-contents">${hljs.highlight(codeLanguage, trimmedCodeContent, true).value}</div>`;
                        const lines = trimmedCodeContent.split('\n').length;
                        for (let i = 1; i <= lines; i++) {
                            const lineNum = document.createElement('div');
                            lineNum.textContent = i;
                            codeBlock.querySelector('.line-numbers').appendChild(lineNum);
                        }
                        codeBlock.querySelector('.copy-btn').onclick = function() {
                            navigator.clipboard.writeText(trimmedCodeContent).then(() => {
                                this.textContent = '已复制';
                                setTimeout(() => {
                                    this.textContent = '复制';
                                }, 2000);
                            });
                        };
                        textDiv.appendChild(codeBlock);
                    } else {
                        textDiv.innerHTML += marked.parse(part);
                    }
                });
            } else {
                textDiv.innerHTML = marked.parse(content);
            }

            const actionsDiv = document.createElement('div');
            actionsDiv.className = 'message-actions';
            const copyButton = document.createElement('div');
            copyButton.className = 'copy-message';
            copyButton.onclick = function() {
                navigator.clipboard.writeText(textDiv.innerText).then(() => {
                    const originalContent = this.innerHTML;
                    this.innerHTML = '<span style="color: #4CAF50;">✓</span>';
                    setTimeout(() => {
                        this.innerHTML = originalContent;
                    }, 1000);
                });
            };
            const deleteButton = document.createElement('div');
            deleteButton.className = 'delete-message';
            deleteButton.onclick = function() {
                messageDiv.remove();
                removeMessageFromStorage(content, role);
            };
            actionsDiv.appendChild(copyButton);
            actionsDiv.appendChild(deleteButton);
            messageDiv.appendChild(actionsDiv);

            messageDiv.appendChild(textDiv);
            messagesDiv.appendChild(messageDiv);
            scrollToBottom();
        }

        function scrollToBottom() {
            const messagesDiv = document.getElementById('chat-messages');
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function removeMessageFromStorage(content, role) {
            let chatHistory = JSON.parse(localStorage.getItem('chatHistory') || '[]');
            chatHistory = chatHistory.filter(item => !(item.content === content && item.role === role));
            localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
        }

        document.getElementById('file-input').addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (!file) return;

            try {
                const ext = file.name.split('.').pop().toLowerCase();
                switch (ext) {
                    case 'pdf':
                        fileContent = await parsePDF(file);
                        break;
                    case 'docx':
                        fileContent = await parseDOCX(file);
                        break;
                    case 'xls':
                    case 'xlsx':
                        fileContent = await parseExcel(file);
                        break;
                    default:
                        fileContent = await readTextFile(file);
                }
                addMessage(`已上传文件：${file.name}`, 'user');
                saveChatHistory(`已上传文件：${file.name}`, 'user');
            } catch (err) {
                alert(`文件解析失败：${err.message}`);
            }
        });

        async function parsePDF(file) {
            const arrayBuffer = await file.arrayBuffer();
            const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
            let text = '';
            for (let i = 1; i <= pdf.numPages; i++) {
                const page = await pdf.getPage(i);
                text += (await page.getTextContent()).items.map(item => item.str).join(' ');
            }
            return text;
        }

        async function parseDOCX(file) {
            const arrayBuffer = await file.arrayBuffer();
            return (await mammoth.extractRawText({ arrayBuffer })).value;
        }

        async function parseExcel(file) {
            const arrayBuffer = await file.arrayBuffer();
            const workbook = XLSX.read(arrayBuffer, { type: 'array' });
            return workbook.SheetNames.map(sheetName =>
                XLSX.utils.sheet_to_csv(workbook.Sheets[sheetName])).join('\n');
        }

        async function readTextFile(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = e => resolve(e.target.result);
                reader.onerror = reject;
                reader.readAsText(file);
            });
        }

        async function sendMessage() {
            const userInput = document.getElementById('user-input');
            const sendButton = document.querySelector('.send-button');
            const fileInput = document.getElementById('file-input');
            const question = userInput.value.trim();

            if (!question && !fileContent) {
                alert("请输入问题或上传文件！");
                return;
            }

            userInput.disabled = true;
            sendButton.classList.add('loading');

            if (fileContent) {
                addMessage(`已上传文件内容：${fileContent.substring(0, 100)}...`, 'user');
                saveChatHistory(`已上传文件内容：${fileContent.substring(0, 100)}...`, 'user');
            }
            addMessage(question, 'user');
            saveChatHistory(question, 'user');
            userInput.value = '';

            contextMessages.push({
                role: "user",
                content: fileContent ? `${question}\n附件内容：${fileContent}` : question
            });

            try {
                switch (currentModel) {
                    case 'kimi':
                        await handleKimiRequest();
                        break;
                    case 'chatgpt':
                        await handleChatGPTRequest();
                        break;
                    case 'claude':
                        await handleClaudeRequest();
                        break;
                    case 'deepseek':
                        await handleDeepSeekRequest();
                        break;
                }
            } catch (error) {
                addMessage(`请求失败：${error.message}`, 'bot');
                saveChatHistory(`请求失败：${error.message}`, 'bot');
            } finally {
                userInput.disabled = false;
                sendButton.classList.remove('loading');
                fileContent = '';
                fileInput.value = '';
            }
        }

        async function handleKimiRequest() {
            const { API_KEY, API_URL, MODEL, TOKEN_LIMIT } = CONFIG.kimi;
            let answerContent = '';

            const response = await fetch(API_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`
                },
                body: JSON.stringify({
                    model: MODEL,
                    messages: contextMessages,
                    stream: true,
                    max_tokens: TOKEN_LIMIT
                })
            });

            const reader = response.body.getReader();
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = new TextDecoder().decode(value);
                chunk.split('\n').filter(line => line.trim()).forEach(line => {
                    try {
                        const data = JSON.parse(line.replace('data: ', ''));
                        if (data.choices[0].delta.content) {
                            answerContent += data.choices[0].delta.content;
                        }
                    } catch (e) { }
                });
            }
            addMessage(answerContent, 'bot', 'kimi');
            saveChatHistory(answerContent, 'bot', 'kimi');

            contextMessages.push({
                role: "assistant",
                content: answerContent
            });
        }

        async function handleChatGPTRequest() {
            const { API_KEY, API_URL, MODEL, TOKEN_LIMIT } = CONFIG.chatgpt;
            let answerContent = '';

            const response = await fetch(API_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`
                },
                body: JSON.stringify({
                    model: MODEL,
                    messages: contextMessages,
                    stream: true,
                    max_tokens: TOKEN_LIMIT
                })
            });

            const reader = response.body.getReader();
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = new TextDecoder().decode(value);
                chunk.split('\n').filter(line => line.trim()).forEach(line => {
                    try {
                        const data = JSON.parse(line.replace('data: ', ''));
                        if (data.choices[0].delta.content) {
                            answerContent += data.choices[0].delta.content;
                        }
                    } catch (e) { }
                });
            }
            addMessage(answerContent, 'bot', 'chatgpt');
            saveChatHistory(answerContent, 'bot', 'chatgpt');

            contextMessages.push({
                role: "assistant",
                content: answerContent
            });
        }

        async function handleClaudeRequest() {
            const { API_KEY, API_URL, MODEL, TOKEN_LIMIT } = CONFIG.claude;
            let answerContent = '';

            const response = await fetch(API_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`
                },
                body: JSON.stringify({
                    model: MODEL,
                    messages: contextMessages,
                    stream: true,
                    max_tokens: TOKEN_LIMIT
                })
            });

            const reader = response.body.getReader();
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = new TextDecoder().decode(value);
                chunk.split('\n').filter(line => line.trim()).forEach(line => {
                    try {
                        const data = JSON.parse(line.replace('data: ', ''));
                        if (data.choices[0].delta.content) {
                            answerContent += data.choices[0].delta.content;
                        }
                    } catch (e) { }
                });
            }
            addMessage(answerContent, 'bot', 'claude');
            saveChatHistory(answerContent, 'bot', 'claude');

            contextMessages.push({
                role: "assistant",
                content: answerContent
            });
        }

        async function handleDeepSeekRequest() {
            const { API_KEY, API_URL, MODEL, REASON_MODEL, TOKEN_LIMIT } = CONFIG.deepseek;
            let answerContent = '';
            let reasoningContent = '';

            const response = await fetch(API_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`
                },
                body: JSON.stringify({
                    model: isReasonMode ? REASON_MODEL : MODEL,
                    messages: contextMessages,
                    stream: true,
                    reasoning_content: true,
                    max_tokens: TOKEN_LIMIT
                })
            });

            const reader = response.body.getReader();
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = new TextDecoder().decode(value);
                chunk.split('\n').filter(line => line.trim()).forEach(line => {
                    try {
                        const data = JSON.parse(line.replace('data: ', ''));
                        if (data.choices[0].delta.content) {
                            answerContent += data.choices[0].delta.content;
                        }
                        if (data.choices[0].delta.reasoning_content) {
                            reasoningContent += data.choices[0].delta.reasoning_content;
                        }
                    } catch (e) { }
                });
            }

            let finalContent = '';
            if (reasoningContent) {
                finalContent += `<span style="color: #999; font-size: 14px;">深度思考<br>${reasoningContent}</span><br><br>`;
            }
            if (answerContent) {
                finalContent += answerContent;
            }
            addMessage(finalContent, 'bot', 'deepseek');
            saveChatHistory(finalContent, 'bot', 'deepseek');

            contextMessages.push({
                role: "assistant",
                content: answerContent
            });
        }

        document.getElementById('user-input').addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        function saveChatHistory(content, role, model = currentModel) {
            let chatHistory = JSON.parse(localStorage.getItem('chatHistory') || '[]');
            chatHistory.push({ content, role, model, timestamp: new Date().getTime() });
            localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
        }

        function loadChatHistory() {
            let chatHistory = JSON.parse(localStorage.getItem('chatHistory') || '[]');
            chatHistory.forEach(item => {
                addMessage(item.content, item.role, item.model);
                contextMessages.push({
                    role: item.role === 'user' ? 'user' : 'assistant',
                    content: item.content
                });
            });
        }

        function clearChatHistory() {
            localStorage.removeItem('chatHistory');
            document.getElementById('chat-messages').innerHTML = '';
            contextMessages = [];
        }

        window.onload = function() {
            loadChatHistory();

            const savedTheme = localStorage.getItem('darkTheme');
            if (savedTheme === 'true') {
                isDarkTheme = true;
                document.body.classList.add('dark-theme');
            }

            const savedModel = localStorage.getItem('currentModel');
            if (savedModel && Object.keys(CONFIG).includes(savedModel)) {
                currentModel = savedModel;
                document.getElementById('model-select').value = currentModel;
                document.getElementById('reason-toggle').style.display =
                    currentModel === 'deepseek' ? 'block' : 'none';
            }
        };
    </script>
</body>
</html>